<template>
  <div class="extra-review-detail">
    <a-card title="审核详情" :loading="loading">
      <template #extra>
        <a-space>
          <a-button @click="$router.back()">返回</a-button>
          <a-button 
            v-if="canApprove" 
            type="primary" 
            @click="handleApprove"
          >
            通过
          </a-button>
          <a-button 
            v-if="canApprove" 
            danger 
            @click="handleReject"
          >
            拒绝
          </a-button>
        </a-space>
      </template>

      <a-descriptions bordered :column="2" style="margin-bottom: 20px">
        <a-descriptions-item label="学生">
          {{ detail.student?.username || '-' }}
          <span v-if="detail.student?.student_id" style="margin-left: 8px; color: #888;">
            ({{ detail.student.student_id }})
          </span>
        </a-descriptions-item>
        <a-descriptions-item label="班级">
          {{ detail.student?.class_name || detail.classes || '-' }}
        </a-descriptions-item>
        <a-descriptions-item label="证书类别">
          {{ detail.sort }}
        </a-descriptions-item>
        <a-descriptions-item label="证书名称">
          {{ detail.name }}
        </a-descriptions-item>
        <a-descriptions-item label="级别">
          {{ detail.ranks }}
        </a-descriptions-item>
        <a-descriptions-item label="等级">
          {{ detail.levels }}
        </a-descriptions-item>
        <a-descriptions-item label="年份">
          {{ detail.time || '-' }}
        </a-descriptions-item>
        <a-descriptions-item label="分数">
          <a-tag v-if="detail.grade" color="green">{{ detail.grade }} 分</a-tag>
          <span v-else>-</span>
        </a-descriptions-item>
        <a-descriptions-item label="提交时间" :span="2">
          {{ detail.created_at ? new Date(detail.created_at).toLocaleString() : '-' }}
        </a-descriptions-item>
      </a-descriptions>

      <a-divider>审核状态</a-divider>

      <a-steps :current="currentStep" status="process">
        <a-step title="班委审核">
          <template #description>
            <a-tag v-if="detail.third_efficient" color="green">已通过</a-tag>
            <a-tag v-else color="orange">待审核</a-tag>
          </template>
        </a-step>
        <a-step title="辅导员审核">
          <template #description>
            <a-tag v-if="detail.second_efficient" color="green">已通过</a-tag>
            <a-tag v-else-if="detail.third_efficient" color="orange">待审核</a-tag>
            <a-tag v-else color="gray">未开始</a-tag>
          </template>
        </a-step>
        <a-step title="学工办审核">
          <template #description>
            <a-tag v-if="detail.first_efficient" color="green">已通过</a-tag>
            <a-tag v-else-if="detail.second_efficient" color="orange">待审核</a-tag>
            <a-tag v-else color="gray">未开始</a-tag>
          </template>
        </a-step>
      </a-steps>

      <a-divider v-if="detail.auditor">审核记录</a-divider>

      <div v-if="detail.auditor" class="audit-records">
        <a-timeline>
          <a-timeline-item 
            v-for="(record, index) in auditRecords" 
            :key="index"
            :color="record.type === 'reject' ? 'red' : 'green'"
          >
            <template #dot>
              <check-circle-outlined v-if="record.type === 'approve'" style="font-size: 16px; color: #52c41a;" />
              <close-circle-outlined v-else style="font-size: 16px; color: #ff4d4f;" />
            </template>
            <div>
              <div style="font-weight: bold;">
                {{ record.auditor }} 
                <a-tag :color="record.type === 'reject' ? 'red' : 'green'" size="small">
                  {{ record.level }}
                </a-tag>
              </div>
              <div v-if="record.remark" style="margin-top: 4px; color: #666;">
                {{ record.remark }}
              </div>
            </div>
          </a-timeline-item>
        </a-timeline>
      </div>

      <a-divider>证书图片</a-divider>

      <div class="certificate-image">
        <a-image
          v-if="detail.picture_url || detail.picture"
          :src="detail.picture_url || detail.picture"
          :alt="detail.name"
          style="max-width: 600px;"
        />
        <a-empty v-else description="暂无证书图片" />
      </div>
    </a-card>

    <!-- 拒绝原因弹窗 -->
    <a-modal
      v-model:open="rejectModalVisible"
      title="拒绝原因"
      @ok="submitReject"
      @cancel="rejectReason = ''"
    >
      <a-form-item label="拒绝原因" required>
        <a-textarea
          v-model:value="rejectReason"
          placeholder="请输入拒绝原因"
          :rows="4"
        />
      </a-form-item>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { message } from 'ant-design-vue'
import { CheckCircleOutlined, CloseCircleOutlined } from '@ant-design/icons-vue'
import { extraReviewAPI } from '@/api/extraReview'
import type { ExtraReview } from '@/api/extraReview'

const route = useRoute()
const router = useRouter()
const loading = ref(false)
const reviewId = Number(route.params.id)
const rejectModalVisible = ref(false)
const rejectReason = ref('')

const detail = ref<ExtraReview>({
  id: reviewId,
  sort: '',
  name: '',
  ranks: '',
  levels: '',
  first_efficient: false,
  second_efficient: false,
  third_efficient: false,
  created_at: '',
  updated_at: ''
})

// 解析审核记录
const auditRecords = computed(() => {
  if (!detail.value.auditor) return []
  
  const records: Array<{
    auditor: string
    level: string
    type: 'approve' | 'reject'
    remark?: string
  }> = []
  
  // auditor 格式："username(level): remark;" 或 "username(level);" 或 "username(拒绝-level): reason;"
  const parts = detail.value.auditor.split(';').filter(p => p.trim())
  
  parts.forEach(part => {
    if (part.includes('拒绝')) {
      // 拒绝记录格式：username(拒绝-level): reason
      const match = part.match(/(.+?)\(拒绝-(.+?)\):\s*(.+)/)
      if (match) {
        records.push({
          auditor: match[1].trim(),
          level: getLevelName(match[2].trim()),
          type: 'reject',
          remark: match[3].trim()
        })
      }
    } else {
      // 通过记录格式：username(level): remark 或 username(level)
      const matchWithRemark = part.match(/(.+?)\((.+?)\):\s*(.+)/)
      const matchWithoutRemark = part.match(/(.+?)\((.+?)\)/)
      
      if (matchWithRemark) {
        // 有备注
        records.push({
          auditor: matchWithRemark[1].trim(),
          level: getLevelName(matchWithRemark[2].trim()),
          type: 'approve',
          remark: matchWithRemark[3].trim()
        })
      } else if (matchWithoutRemark) {
        // 无备注
        records.push({
          auditor: matchWithoutRemark[1].trim(),
          level: getLevelName(matchWithoutRemark[2].trim()),
          type: 'approve'
        })
      }
    }
  })
  
  return records
})

// 获取级别名称
const getLevelName = (level: string): string => {
  const levelMap: Record<string, string> = {
    'first': '学工办审核',
    'second': '辅导员审核',
    'third': '班委审核'
  }
  return levelMap[level] || level
}

// 当前审核步骤
const currentStep = computed(() => {
  if (detail.value.first_efficient) return 3 // 全部通过
  if (detail.value.second_efficient) return 2 // 辅导员已审
  if (detail.value.third_efficient) return 1 // 班委已审
  return 0 // 待班委审核
})

// 判断当前用户是否可以审核
const canApprove = computed(() => {
  // 如果全部审核都通过了，不能再审核
  if (detail.value.first_efficient && detail.value.second_efficient && detail.value.third_efficient) {
    return false
  }
  // 其他情况下，只要status是pending就可以审核
  return detail.value.status === 'pending'
})

// 加载详情
const loadDetail = async () => {
  if (!reviewId) {
    message.error('审核ID无效')
    router.back()
    return
  }

  loading.value = true
  try {
    const res = await extraReviewAPI.getExtraReviewDetail(reviewId)
    detail.value = res.data
  } catch (error: any) {
    message.error('加载详情失败: ' + (error.response?.data?.message || error.message))
    router.back()
  } finally {
    loading.value = false
  }
}

// 审核通过
const handleApprove = async () => {
  // 根据当前步骤确定审核级别
  let level: 'first' | 'second' | 'third' = 'third'
  if (detail.value.second_efficient) {
    level = 'first' // 学工办审核
  } else if (detail.value.third_efficient) {
    level = 'second' // 辅导员审核
  }

  try {
    await extraReviewAPI.approveExtraReview(reviewId, level)
    message.success('审核通过')
    loadDetail() // 重新加载数据
  } catch (error: any) {
    message.error('审核失败: ' + (error.response?.data?.message || error.message))
  }
}

// 打开拒绝弹窗
const handleReject = () => {
  rejectModalVisible.value = true
}

// 提交拒绝
const submitReject = async () => {
  if (!rejectReason.value) {
    message.error('请输入拒绝原因')
    return
  }

  // 根据当前步骤确定审核级别
  let level: 'first' | 'second' | 'third' = 'third'
  if (detail.value.second_efficient) {
    level = 'first'
  } else if (detail.value.third_efficient) {
    level = 'second'
  }

  try {
    await extraReviewAPI.rejectExtraReview(reviewId, level, rejectReason.value)
    message.success('已拒绝')
    rejectModalVisible.value = false
    rejectReason.value = ''
    router.back()
  } catch (error: any) {
    message.error('操作失败: ' + (error.response?.data?.message || error.message))
  }
}

onMounted(() => {
  loadDetail()
})
</script>

<style scoped>
.certificate-image {
  text-align: center;
  padding: 20px;
}

.audit-records {
  margin-top: 20px;
  padding: 16px;
  background-color: #fafafa;
  border-radius: 4px;
}
</style>
